#!/usr/bin/env python

import sys, os

from twisted.python import log
from twisted.internet import reactor
from twisted.web import client
from twisted.internet import defer, task
from twisted.internet import reactor

from polarrose.amazon.sdb import SimpleDatabaseService

if __name__ == "__main__":

    def printResult(response):
        if response.success:
            for i in response.items:
                print "%s: %s" % (i.name,i.attributes)
        else:
            print "The request failed with the following errors:"
            for code,message in response.errors.iteritems():
                print " %s - %s" % (code, message)            
        reactor.stop()

    def printError(failure):
        print "failure: " + str(failure)
        reactor.stop()

    limit = 10
    if len(sys.argv) == 4:
        limit = int(sys.argv[3])

    service = SimpleDatabaseService(key = os.environ.get("AWS_KEY"), secret = os.environ.get("AWS_SECRET"))
    service.fetch(sys.argv[1], sys.argv[2], maxNumberOfItems = limit).addCallback(printResult).addErrback(printError)
    reactor.run()
    
    print "Total box usage: %s" % service.totalBoxUsage
